import React from 'react'
import { findDOMNode } from 'react-dom'; 
import 'sq-ui/lib/common.css';
import 'animate.css'
import '../../ui/reset.styl'
import style from './style'
import Header from './Header'
import SimpleHeader from './SimpleHeader'
import Content from './Content'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as appAction from '../../actions/app.action'
import { fetchSearchList, fetchAtList, clearAtList } from '../../actions/home.action'
import { fetchOrg } from '../../actions/system.action'
import { logout } from '../../actions/auth.action'
import { u } from '../../actions/util'
import Toast from '../../ui-components/toast'
import util from '../../util'
import { tip } from 'sq-ui';
import cx from 'classnames';
import { Modal, Tooltip } from '../../ui-components';
import { Button } from 'sq-ui'; 

tip.setBus(util.bus);

// 顶层注入action函数
@connect(({app}) => ({app}), dispatch => ({actions: bindActionCreators( { ...appAction, fetchSearchList, fetchAtList, clearAtList, fetchOrg, logout} , dispatch)}))
class App extends React.Component {

  static childContextTypes = {
    onContentScroll: React.PropTypes.func.isRequired,
  }

  state = {
    freeze_guide: null,
    // welcome video
    showVideo: false,
  };

  getChildContext() {
    return {
      onContentScroll: this.onContentScroll,
    };
  }
  onContentScroll = (top) => {
    const content = findDOMNode(this.refs.content);
    content.scrollTop = top;
  }

	static contextTypes = {
		router: React.PropTypes.object
	}

  // url或者参数发生变化后，清除掉toast
  clearToast() {
    Toast.hide()
  }

  componentDidUpdate(props) {
    const content = findDOMNode(this.refs.content);
    if (props.location.pathname != this.props.location.pathname) {
      content.scrollTop = 0;
      this.clearToast()
    } else if (!util.isShallowEqual(props.location.query, this.props.location.query)) {
      content.scrollTop = 0;
      this.clearToast()
    }
  }

  componentWillReceiveProps(props) {
    if (props.location.pathname != this.props.location.pathname) {
      this.clearToast()
    } else if (!util.isShallowEqual(props.location.query, this.props.location.query)) {
      this.clearToast()
    }

    if (util.isNull(this.props.app.org) && !util.isNull(props.app.org)) {
      if (props.app.org.isNaviOrg) {
        this.props.actions.getGuide();
      }
    }

    const { pathname, query } = props.location;
    const { naviStep, profile, guide, org } = props.app;

    if (pathname != this.props.pathname || !this.props.pathname) {
      if (naviStep == null || guide == null) return;
      if (naviStep == 8) this.setState({ freeze_guide: 0 });
      if (naviStep == 0) {
        this.setState({ freeze_guide: 0, showVideo: true });
        return;
      } else {
        // 停止视频
        if (this.props.app.naviStep == 0) {
          this.setState({
            showVideo: false,
          });
        }
      }
      if (naviStep > 1 && naviStep < 8) {
        if (naviStep == 7) {
          if ((!(pathname.indexOf('/okr') === 0 && query.type == 1 && query.teamId == (org.teamVO || {}).teamId) || pathname.indexOf('/okr/objectives') === 0) && !(pathname.indexOf('/objectives') === 0 && query.teamId == (org.teamVO || {}).teamId)) {
            this.props.actions.freezeGuide(true);
            this.setState({
              freeze_guide: true,
            });
          } else {
            this.props.actions.freezeGuide(false);
            this.setState({
              freeze_guide: 0,
            });
            if (guide != 4) {
              if (pathname.indexOf('/objectives') === 0) {
                this.props.actions.setStepGuide(4);
              }
            }
          }
          return;
        }else{
          if (!(pathname.indexOf('/okr') === 0 && query.type == 2 && query.teamId == profile.teamVO.teamId) || pathname.indexOf('/okr/objectives') === 0) {
            this.props.actions.freezeGuide(true);
            this.setState({
              freeze_guide: true,
            });
          } else {
            this.props.actions.freezeGuide(false);
            this.setState({
              freeze_guide: 0,
            });
          }
        }
      }
      else if (naviStep == 1) {
        if (pathname != '/home') {
          this.props.actions.freezeGuide(true);
          this.setState({
            freeze_guide: true,
          })
        } else {
          this.props.actions.freezeGuide(false);
          this.setState({
            freeze_guide: 0,
          })
        }
      }
    }
  }

	componentDidMount() {
    if (u.userId) {
      this.props.actions.fetchProfile(u.userId)
      this.props.actions.fetchUserProfile(u.userId)
      this.props.actions.fetchOrg()
      this.props.actions.fetchUnreadNumber()
      this.props.actions.fetchUserIdentifyProfile(u.userId, u.orgId); // 查询用户所属部门数据
    }

    const content = findDOMNode(this.refs.content);
    content.addEventListener('scroll', () => {
      util.bus.emit('page:scroll', content.scrollTop)
    });

    window.onresize = () => {
      util.bus.emit('page:resize')
    }
	}

	render() {
		const { app, ...others } = this.props
		return (
      <div className={style.root}>
        {
          u.userId?
          <Header 
            router={this.context.router}
            location={this.props.location}
            {...this.props.actions}
            {...app}
          />
          : <SimpleHeader router={this.context.router} {...this.props.actions} {...app}/>
        }
        <Content
          ref="content"
          {...app}
          {...others}
          freeze_guide={this.state.freeze_guide}
          router={this.context.router}
        />
				<Toast/>
        <Modal
          shouldCloseOnOverlayClick={false}
          onRequestClose={() => {
            this.setState({
              showVideo: false,
            });
          }}
          active={this.state.showVideo}
          title="欢迎使用Better OKR"
        >
          {
          <div className={style['guide-start']}>
            <div className={style['guide-start-video']}>
              <video
                ref="video"
                className={style['guide-start-video-container']}
                src="http://front.wozaihcm.com/video/preview_1.mp4"
                preload="auto"
              >
              </video>
            </div>
            <div ref="play" className={style['guide-start-hint']} onClick={() => {this.refs.video.play();this.refs.play.style.opacity = '0';}}>点击播放</div>
            <Button
              blue
              label={'开始演示'}
              style={{textAlign: 'center',marginTop:'-10px'}}
              onClick={() => {
                this.props.actions.updateGuide(1);
                this.props.router.push('/');
              }}
            />
          </div>
          }
        </Modal>
			</div>
		)
	}
}

export default App
